package com.wonder.admin.controller;


import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.wonder.admin.domain.SysAdmin;

import com.wonder.admin.domain.SysRole;
import com.wonder.admin.domain.vo.LoginBody;
import com.wonder.admin.domain.vo.SysMenuVo;
import com.wonder.admin.service.SysAdminService;
import com.wonder.admin.service.SysConfigService;

import com.wonder.admin.service.SysMenuService;
import com.wonder.admin.service.impl.SysRoleServiceImpl;

import com.wonder.common.common.AjaxMap;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.config.WonderConfig;
import com.wonder.common.constants.Constants;
import com.wonder.framework.authorization.CheckAdminToken;

import com.wonder.framework.service.CaptchaService;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.utils.StringUtils;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**   
 * 
 * <p>说明： 后台用户API接口层</P>
 * @version: V1.0
 * @author: LuZhongren
 * @time    2022年1月27日
 *
 */
@Api(tags = "用户登录")
@RestController
@RequestMapping("/admin/Login")
public class SysLoginController {
	
//	@Resource(name = "captchaProducer")
//    private Producer captchaProducer;
//
//    @Resource(name = "captchaProducerMath")
//    private Producer captchaProducerMath;
//
//    @Autowired
//    private RedisCache redisCache;
//    
//    // 验证码类型
//    @Value("${wonder.captchaType}")
//    private String captchaType;
	
	@Autowired
	private CaptchaService captchaService;
    
    @Autowired
    private SysAdminService adminService;
    
    @Autowired
    private CheckAdminToken checkAdminToken;
    
    
    @Autowired
    private SysRoleServiceImpl sysRoleService;
    
    @Autowired
    private SysMenuService sysMenuService;
    
    @Autowired
    private SysConfigService sysConfigService;
    
    
    
    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation(value = "登录")
    @RequestMapping(value = "/index", method = RequestMethod.POST)
    public Map<String, Object> login(@RequestBody LoginBody loginBody) throws Exception
    {
        // 生成令牌
    	//loginBody.setCode("12345678WonderSoftwareEngineering");//For test,
        String token = adminService.login(loginBody);
        return AjaxMap.success(Constants.TOKEN, token);
        
    }
    
    @ApiOperation(value="登出")
    @RequestMapping(value = "/logout")
    public AjaxResult<Map<String, String>> logout(HttpServletRequest request) throws Exception {
        String token = checkAdminToken.getTokenFormRequest(request);
        adminService.logout(token);
        return AjaxResult.success(MessageUtils.message("user.logout.success"));
    }
    
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     * @throws Exception 
     */
    @ApiOperation(value = "获取用户信息")
    @RequestMapping("/getUserInfo")
    public Map<String, Object> getUserInfo(HttpServletRequest request) throws Exception
    {
        String token = checkAdminToken.getTokenFormRequest(request);
        SysAdmin user = adminService.getAdminByToken(token);
        if(user==null) return AjaxMap.failed(MessageUtils.message("user.token.not.effect")) ;
        SysRole role=sysRoleService.getById(user.getRole_id());
        List<SysMenuVo> menus=sysMenuService.getBaseMenus(role);
        List<Map<String,Object>> components=sysMenuService.getComponents(menus);
        if(role.getRole_id()==1) {
        	Map<String,Object> map1=new HashMap<String,Object>();
        	map1.put("name", "Field");
        	map1.put("path", "/admin/Field/index.html");
			Map<String,Object> metaMap1=new HashMap<String, Object>();
			metaMap1.put("title", "字段管理");
			map1.put("meta",metaMap1 );
        	map1.put("component_path", "admin/sys/field/Index.vue");
        	
        	Map<String,Object> map2=new HashMap<String,Object>();
        	map2.put("name", "Action");
        	map2.put("path", "/admin/Action/index.html");
			Map<String,Object> metaMap=new HashMap<String, Object>();
			metaMap.put("title", "方法管理");
			map2.put("meta",metaMap );
        	map2.put("component_path", "admin/sys/action/Index.vue");
        	
        	Map<String,Object> map3=new HashMap<String,Object>();
        	map3.put("name", "Api");
        	map3.put("path", "/admin/Api/index.html");
			Map<String,Object> metaMap2=new HashMap<String, Object>();
			metaMap2.put("title", "API接口");
			map3.put("meta",metaMap2 );
			map3.put("component_path", "admin/sys/api/Index.vue");
        	
        	components.add(map1);
        	components.add(map2);
        	components.add(map3);
        }
        
        components.addAll(sysMenuService.getHiddenComponents(role));
    
        Map<String, Object> result = new HashMap<>();
        result.put("menu", menus);
        result.put("components", components);
        result.put("actions", StringUtils.split(role.getAccess_table(), ','));
        
        Map<String, Object> userInfo=new HashMap<>();
        userInfo.put("user", user.getUser());
        userInfo.put("role_id", user.getRole_id());
        
        Map<String,Object> configMap=sysConfigService.getSysConfig();
        userInfo.put("site_title", configMap.get("site_title"));
        userInfo.put("headimg", configMap.get("logo"));
        userInfo.put("show_notice", true);
        
        result.put("data", userInfo);

        return AjaxMap.success(result);
  
    }
    
	/**
	 * @explain 获取验证码  <swagger GET请求>
	 * @param   对象参数：id
	 * @return  JsonResult
	 * @author  LuZhongren
	 * @time    2022年1月27日
	 */
	@RequestMapping("/verify")
	@ApiOperation(value = "获取验证码", notes = "作者：LuZhongren")
	public Map<String,Object> verify(HttpServletResponse response) throws IOException
    {
		Map<String, Object> map=captchaService.Captcha();
//        // 保存验证码信息
//        String uuid = IdUtils.simpleUUID();
//        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
//
//        String capStr = null, code = null;
//        BufferedImage image = null;
//
//        // 生成验证码
//        if ("math".equals(captchaType))
//        {
//            String capText = captchaProducerMath.createText();
//            capStr = capText.substring(0, capText.lastIndexOf("@"));
//            code = capText.substring(capText.lastIndexOf("@") + 1);
//            image = captchaProducerMath.createImage(capStr);
//        }
//        else if ("char".equals(captchaType))
//        {
//            capStr = code = captchaProducer.createText();
//            image = captchaProducer.createImage(capStr);
//        }
//
//        redisCache.set(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
//        System.out.println("验证图形码：" +verifyKey+" "+ code+"  UUID:"+uuid);
//        // 转换流信息写出
//        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
//        try
//        {
//            ImageIO.write(image, "jpg", os);
//        }
//        catch (IOException e)
//        {
//            return AjaxMap.failed(e.getMessage());
//        }
//
//        Map<String,Object> data=new HashMap<String,Object>();
//        data.put("key", uuid);
//        data.put("img", Base64.encode(os.toByteArray()));
//        
//        
//        Map<String,Object> map=new HashMap<String,Object>();
//        map.put("data", data);
//        map.put("rememberMe", true);
        
        Map<String,Object> configMap=sysConfigService.getSysConfig();
        map.put("site_title", configMap.get("site_title"));//Later this will get from config
        map.put("success_url", "/admin/Home/index.html");
        map.put("verify_status",true);//get from sys_config table
        map.put("google_auth", WonderConfig.isGoogleAuth());
        
        
        
        return AjaxMap.success(map);
    
    }

}
